package idv.cjcat.stardust.common;

import java.util.Hashtable;
import org.w3c.dom.Element;

import idv.cjcat.stardust.common.xml.XMLElement;
import idv.cjcat.stardust.common.xml.XMLBuilder;
import idv.cjcat.stardust.common.xml.XMLConvertible;

/**
 * All Stardust elements are subclasses of this class.
 */
public class StardustElement implements XMLConvertible {
	
	private static Hashtable<String,Integer> elementCounter = new Hashtable<String,Integer>();
	
	public String name;
	
	public StardustElement() {
		String str = getXMLTagName();
		
		if (!elementCounter.containsKey(str)) elementCounter.put(str, 0);
		else elementCounter.put(str, elementCounter.get(str)+1);
		
		this.name = str + "_" + elementCounter.get(str);
	}
	
	//XML
	//------------------------------------------------------------------------------------------------
	
	/**
	 * [Abstract Method] Returns the related objects of the element.
	 * 
	 * <p>
	 * This tells the <code>XMLBuilder</code> which elements are related, 
	 * so the builder can include them in the XML representation.
	 * </p>
	 * @return
	 */
	public StardustElement[] getRelatedObjects() {
		return new StardustElement[0];
	}
	
	/**
	 * [Abstract Method] Returns the name of the root node of the element's XML representation.
	 * @return
	 */
	public String getXMLTagName() {
		return "StardustElement";
	}
	
	/**
	 * Returns the root tag of the XML representation.
	 * @return
	 */
	public final Element getXMLTag() {
		Element xml = XMLElement.document.createElement(getXMLTagName());
		xml.setAttribute("name", name);
		return xml;
	}
	
	/**
	 * [Abstract Method] Returns the tag for containing elements of the same type.
	 * @return
	 */
	public Element getElementTypeXMLTag() {
		return XMLElement.document.createElement("elements");
	}
	
	/**
	 * [Abstract Method] Generates XML representation.
	 * @param	nameOnly
	 * @return
	 */
	public Element toXML() {
		Element xml = getXMLTag();
		return xml;
	}
	
	/**
	 * [Abstract Method] Reconstructs the element from XML representations.
	 * @param	xml
	 * @param	builder
	 */
	public void parseXML(Element xml){
		parseXML(xml, null);
	}
	public void parseXML(Element xml, XMLBuilder builder){
		name = xml.getAttribute("name");
	}
	
	//------------------------------------------------------------------------------------------------
	//end of XML
	
}